package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.pinda.DTO.truck.TruckLicenseDto;
import com.itheima.pinda.entity.truck.PdTruck;
import com.itheima.pinda.entity.truck.PdTruckLicense;
import com.itheima.pinda.mapper.PdTruckLicenseMapper;
import com.itheima.pinda.mapstruct.TruckDTO2Entity;
import com.itheima.pinda.service.PdTruckLicenseService;
import com.itheima.pinda.service.PdTruckService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class PdTruckLicenseServiceImpl extends ServiceImpl<PdTruckLicenseMapper, PdTruckLicense> implements PdTruckLicenseService {


    @Resource
    private TruckDTO2Entity truckDTO2Entity;

    @Resource
    private PdTruckService pdTruckService;

    /**
     * 保存车辆行驶证信息
     *
     * @param dto 车辆行驶证信息
     * @return 车辆行驶证信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TruckLicenseDto saveTruckLicense(TruckLicenseDto dto) {
        PdTruckLicense pdTruckLicense = truckDTO2Entity.conver(dto);
        if (pdTruckLicense.getId() == null) {
            super.save(pdTruckLicense);
            // 处理 pd_truck 车辆信息中的关联字段
            if (StringUtils.isNotBlank(pdTruckLicense.getTruckId())) {
                PdTruck pdTruck = pdTruckService.getById(pdTruckLicense.getTruckId());
                pdTruck.setTruckLicenseId(String.valueOf(pdTruckLicense.getId()));
                pdTruckService.updateById(pdTruck);
            }
        } else {
            super.updateById(pdTruckLicense);
        }

        // todo 这里逻辑可奇怪 -- 待联调解决
        // if (StringUtils.isBlank(dto.getId())) {
        //     PdTruck pdTruck = new PdTruck();
        //     pdTruck.setId()
        // }
        dto = truckDTO2Entity.conver(pdTruckLicense);
        return dto;
    }
}
